#region Imported Namespaces
using System;
using Workflow.NET;
using WorkFlowEngine = Workflow.NET.Engine;
using WorkFlowAction = Workflow.NET.ActionHandler;
using WorFlowInterface = Workflow.NET.Engine.Interfaces;
using PHSRAG.Insight21.Policy;
using System.Collections;
using InsightHumans = PHSRAG.Insight21.Humans;
using System.Threading;
using System.Data.SqlClient;
using System.Data;
using System.Web;
using PHSRAG.Utility;
#endregion
namespace PHSRAG.Insight21.InsightWorkFlow
{
    #region Class SetAnimalsWorkFlowVariables
    /// <summary>
    /// This is a Skelta workflow custom action class. This class is setting Workflow variables (Example: PI User Id array - piArray
    /// Ancillary) for current Workflow item. IActionRun is Skelta interface to implement custom actions. 
    /// Actions.xml of particular application needs to be configured so that this action
    /// becomes accesible from Skelta Workflow Manager control under List of Actions -> Custom Actions. 	
    /// </summary>
    public class SetAnimalsWorkFlowVariables : Workflow.NET.Engine.Interfaces.IActionRun
    {
        /// <summary>
        /// Default constructor
        /// </summary>
        public SetAnimalsWorkFlowVariables()
        {

        }

        /// <summary>
        /// Custom action method used by Skelta Workflow engine to take certain action. This is used to set workflow variables
        /// for each Workflow item. This method gets called just before protocol gets assigned to PI and also after every submitter's
        /// accept step. This method calls HumansWorkflow assembly and gets all users for different roles assigned for particular
        /// Protocol Process. When Protocol PRoces gets submitted to Workflow all the related parameters (like Protocol Id, Protocol ProcessId)
        /// get passed to the Workflow. They get saved in the Workflow context for every item. These parameters get used to grab all users
        /// involved in the Workflow for that particular Protocol Process. All these users are saved in different arrays. These arrays get used
        /// in designing the process (E.g. In Workflow manager on PI Step "To" property of PI approval step gets configured with "UserId IN piUser" 
        /// where PIUser is an array which gets set in this method.)
        /// Submitters can change the Staff assignment that is why this step gets called from each Submitter Aceept step as well.
        /// </summary>
        /// <param name="executionId">Workflow execution Id - a unique id used for each workflow item</param>
        /// <param name="executionDetailsId">Execution detail Id - Id used for execution detail table</param>
        /// <param name="currentContext">Context class which encapsulates all the information about the executing Workflow.</param>
        /// <param name="currentAction">Current Workflow action</param>
        /// <param name="inlinkOutput">Output in string format which has come from the step before this step</param>
        /// <param name="retry">Boolean retry variable</param>
        /// <param name="output">Output value which is used by Skelta Workflow manager to takce certain path in the process.</param>
        /// <returns>The result of an action execution. Either execution is complete or action is in sleep mode.  </returns>
        public WorFlowInterface.ActionResult Run(int executionId, int executionDetailsId, WorkFlowEngine.Context currentContext, Action currentAction, string inlinkOutput, bool retry, out string output)
        {
            output = null;
            Log logger = currentContext.log;
            AnimalsWorkFlow AnimalsWF = new AnimalsWorkFlow(new NullCachePolicy());
            try
            {
                object insightApplicationName = currentContext.Contents["insightApplicationName"];
                AnimalsWorkFlow.InsightApplicationName = (null == insightApplicationName) ? string.Empty : ((Content)insightApplicationName).Value.ToString();

                Thread.SetData(Thread.GetNamedDataSlot("Connections"), HumansWorkFlow.Connections);
                //System.Diagnostics.Debugger.Break();		
                //set up variables for the emails in the protocols.
                currentContext.Variables["protocolTitle"].Value = String.Empty;
                currentContext.Variables["piName"].Value = String.Empty;
                currentContext.Variables["submissionType"].Value = String.Empty;
                currentContext.Variables["submitterName"].Value = String.Empty;
                currentContext.Variables["protocolProcessId"].Value = String.Empty;
                currentContext.Variables["submitterOrgName"].Value = String.Empty;
                currentContext.Variables["executionId"].Value = String.Empty;
                currentContext.Variables["comments"].Value = String.Empty;
                String ProtocolNumber = String.Empty;
                String protocolType = String.Empty;
                String submissionType = String.Empty;
                String topChoice = String.Empty;
                bool tissueProtocol = false;
                if (currentContext.Variables["protocolNumber"] != null)
                    currentContext.Variables["protocolNumber"].Value = String.Empty;
                if (currentContext.Variables["environment"] != null)
                    currentContext.Variables["environment"].Value = String.Empty;
                if (currentContext.Variables["environmentAddress"] != null)
                    currentContext.Variables["environmentAddress"].Value = String.Empty;
                if (currentContext.Variables["anciBioUser"] != null)
                    currentContext.Variables["anciBioUser"].Value = 0;
                if (currentContext.Variables["anciChemUser"] != null)
                    currentContext.Variables["anciChemUser"].Value = 0;
                if (currentContext.Variables["anciRadUser"] != null)
                    currentContext.Variables["anciRadUser"].Value = 0;
                if (currentContext.Variables["anciBioUserExist"] != null)
                    currentContext.Variables["anciBioUserExist"].Value = 0;
                if (currentContext.Variables["anciChemUserExist"] != null)
                    currentContext.Variables["anciChemUserExist"].Value = 0;
                if (currentContext.Variables["anciRadUserExist"] != null)
                    currentContext.Variables["anciRadUserExist"].Value = 0;
                if (currentContext.Variables["tissueWorkflow"] != null)
                    currentContext.Variables["tissueWorkflow"].Value = 0;          
                if (currentContext.Variables["moduleType"] != null)
                    currentContext.Variables["moduleType"].Value = String.Empty;
                if (currentContext.Variables["addedStudyStaff"] != null)
                    currentContext.Variables["addedStudyStaff"].Value = String.Empty;
                if (currentContext.Variables["isStudyAdded"] != null)
                    currentContext.Variables["isStudyAdded"].Value = "0";                
                
                SqlDataReader reader = DataAccess.ExecuteReader(DataAccess.GetConnectionString(), 
                                                                "GetRunEnvironment");

                if (reader.Read())
                {
                    if (currentContext.Variables["environment"] != null)
                        currentContext.Variables["environment"].Value = reader["RunEnvironmentName"].ToString();
                    if (currentContext.Variables["environmentAddress"] != null)
                        currentContext.Variables["environmentAddress"].Value = reader["RunEnvironmentAddress"].ToString();                   
                }

                reader.Close();
                reader.Dispose();

                if (executionId != 0)
                {
                    currentContext.Variables["executionId"].Value = executionId;

                    reader = DataAccess.ExecuteReader(DataAccess.GetConnectionString(), 
                                                        "GetExecutionDetails", 
                                                        DataAccess.BuildSqlParameterArray("@executionId", SqlDbType.Int, executionId));

                    if (reader.Read())
                    {
                        currentContext.Variables["protocolTitle"].Value = reader["ProtocolTitle"].ToString();
                        currentContext.Variables["piName"].Value = reader["PIName"].ToString();
                        currentContext.Variables["submissionType"].Value = reader["SubmissionType"].ToString();
                        currentContext.Variables["submitterName"].Value = reader["SubmitterName"].ToString();
                        currentContext.Variables["protocolProcessId"].Value = reader["ProtocolProcessId"].ToString();
                        currentContext.Variables["submitterOrgName"].Value = reader["OrgName"].ToString();
                        if (currentContext.Variables["protocolNumber"] != null)
                            currentContext.Variables["protocolNumber"].Value = (reader["ProtocolNumber"].ToString() == String.Empty) ? "NA" : reader["ProtocolNumber"].ToString();
                        ProtocolNumber = reader["ProtocolNumber"].ToString();
                        submissionType = reader["SubmissionType"].ToString();
                        if (currentContext.Variables["moduleType"] != null)
                            currentContext.Variables["moduleType"].Value = reader["ModuleType"].ToString();
                        if (currentContext.Variables["prereviewrejectflag"] != null)
                            currentContext.Variables["prereviewrejectflag"].Value = 0;
                        protocolType = reader["ProtocolType"].ToString().ToLower();
                    }
                    reader.Close();
                    reader.Dispose();
                }

                if (protocolType == "protocoltype_atissue")
                {
                    if (currentContext.Variables["tissueWorkflow"] != null)
                        currentContext.Variables["tissueWorkflow"].Value = 1;   
                }

                if (currentContext.Variables["submissionType"].Value.ToString().Contains("TR-InProg"))
                {
                    SqlParameter[] args = DataAccess.BuildSqlParameterArray("@protocolProcessId", SqlDbType.Int, Int32.Parse(currentContext.Contents["ppid"].Value.ToString()),
                                                                            "@protocolNumber", SqlDbType.VarChar, ProtocolNumber);
                    DataAccess.ExecuteNonQuery(DataAccess.GetConnectionString(), "UpdateProtocolStudyStaffToCertifyAgain", args);
                }

                if (currentContext.Variables["submissionType"].Value.ToString().Contains("IR"))
                {
                    SqlParameter[] args = DataAccess.BuildSqlParameterArray("@protocolProcessId", SqlDbType.Int, Int32.Parse(currentContext.Contents["ppid"].Value.ToString()),
                                                                            "@name", SqlDbType.VarChar, "Tissue Application");
                    reader = DataAccess.ExecuteReader(DataAccess.GetConnectionString(), "GetQuestionnaireNameForProcess", args);

                    if (reader.Read())                    
                        tissueProtocol = true;                    
                     
                    reader.Close();
                    reader.Dispose();
                }

                if (currentContext.Variables["submissionType"].Value.ToString().Contains("AME"))
                {
                    reader = DataAccess.ExecuteReader(DataAccess.GetConnectionString(),
                                                    "GetAnswerForProcess", 
                                                    DataAccess.BuildSqlParameterArray
                                                    ("@protocolProcessId", SqlDbType.Int, Int32.Parse(currentContext.Contents["ppid"].Value.ToString())
                                                    ));

                    while (reader.Read())
                    {
                        if (reader["Name"].ToString().ToLower() == "topchoice")
                            topChoice = reader["Value"].ToString().ToLower();

                        if (reader["Name"].ToString().ToLower() == "comstaff")
                        {
                            if (currentContext.Variables["isStudyAdded"] != null)
                                currentContext.Variables["isStudyAdded"].Value = (topChoice == "y") ? "1" : "0";
                        }
                    }


                    reader.Close();
                    reader.Dispose();
                }

                //Get Submitter
                currentContext.Variables["submitterUser"].Value = AnimalsWF.GetWorkFlowUsers(Int32.Parse(currentContext.Contents["protocolid"].Value.ToString()), Int32.Parse(currentContext.Contents["ppid"].Value.ToString()), InsightHumans.Constants.WorkflowRoleType.Submitter);

                //Get Principal Investigator						 			
                currentContext.Variables["piUser"].Value = AnimalsWF.GetWorkFlowUsers(Int32.Parse(currentContext.Contents["protocolid"].Value.ToString()), Int32.Parse(currentContext.Contents["ppid"].Value.ToString()), InsightHumans.Constants.StaffRoleType.PrincipalInvestigator);

                //Get SRAC Intake Person	
                if (tissueProtocol)
                    currentContext.Variables["SRACIntakeUser"].Value = AnimalsWF.GetWorkFlowUsers(Int32.Parse(currentContext.Contents["protocolid"].Value.ToString()), Int32.Parse(currentContext.Contents["ppid"].Value.ToString()), InsightHumans.Constants.WorkflowRoleType.SRACIntakeTissueUser);
                else
                    currentContext.Variables["SRACIntakeUser"].Value = AnimalsWF.GetWorkFlowUsers(Int32.Parse(currentContext.Contents["protocolid"].Value.ToString()), Int32.Parse(currentContext.Contents["ppid"].Value.ToString()), InsightHumans.Constants.WorkflowRoleType.SRACIntakeUser);

                //Get SRAC PreView People	
                if (currentContext.Variables["SRACPreviewUsers"] != null)
                {
                    if (topChoice == "y")
                    {
                        currentContext.Variables["SRACPreviewUsers"].Value = AnimalsWF.GetWorkFlowUsers(Int32.Parse(currentContext.Contents["protocolid"].Value.ToString()), Int32.Parse(currentContext.Contents["ppid"].Value.ToString()), InsightHumans.Constants.WorkflowRoleType.SRACPreViewAMEStaffY);
                        if (currentContext.Variables["isStudyAdded"] != null)
                        {
                            if (currentContext.Variables["isStudyAdded"].Value.ToString() == "1")
                            {
                                currentContext.Variables["addedStudyStaff"].Value = AnimalsWF.GetAmeNewWorkFlowUsers(Int32.Parse(currentContext.Contents["ppid"].Value.ToString()));
                            }
                        }
                    }
                    else if (topChoice == "n")
                        currentContext.Variables["SRACPreviewUsers"].Value = AnimalsWF.GetWorkFlowUsers(Int32.Parse(currentContext.Contents["protocolid"].Value.ToString()), Int32.Parse(currentContext.Contents["ppid"].Value.ToString()), InsightHumans.Constants.WorkflowRoleType.SRACPreViewAMEStaffN);
                    else if (topChoice == String.Empty)
                        currentContext.Variables["SRACPreviewUsers"].Value = AnimalsWF.GetWorkFlowUsers(Int32.Parse(currentContext.Contents["protocolid"].Value.ToString()), Int32.Parse(currentContext.Contents["ppid"].Value.ToString()), InsightHumans.Constants.WorkflowRoleType.SRACPreViewUsers);
                }
                
                //Get Contact people
                currentContext.Variables["contactPeopleUser"].Value = AnimalsWF.GetContactPeople(Int32.Parse(currentContext.Contents["ppid"].Value.ToString()));

                //Get Protocol Administrator
                currentContext.Variables["protocolAdministrator"].Value = AnimalsWF.GetProtocolAdministrator(Int32.Parse(currentContext.Contents["ppid"].Value.ToString()));

                //Get Workflow Administrator
                currentContext.Variables["workflowAdministrator"].Value = AnimalsWF.GetWorkflowPeople(1, "AnimalsWorkflowAdmin", Int32.Parse(currentContext.Contents["ppid"].Value.ToString()));

                //Get Workflow Administrator
                currentContext.Variables["compliancePeople"].Value = AnimalsWF.GetWorkflowPeople(2, "CompliancePerson", Int32.Parse(currentContext.Contents["ppid"].Value.ToString()));

                //Get Workflow Error Administrator
                currentContext.Variables["workflowErrorAdministrator"].Value = AnimalsWF.GetWorkflowPeople(1, "AnimalsWorkflowErrorAdmin", Int32.Parse(currentContext.Contents["ppid"].Value.ToString()));

                //Get Ancillary board user                              
                //ArrayList varAnciArrayList = new ArrayList();
                Hashtable anciHash = AnimalsWF.GetAnimalsAncillaryBoardUsers(Int32.Parse(currentContext.Contents["protocolid"].Value.ToString()), Int32.Parse(currentContext.Contents["ppid"].Value.ToString()));

                if (anciHash != null && anciHash.Count > 0 && submissionType != String.Empty)
                {
                    currentContext.Variables["boardUsersExist"].Value = 1;

                    ArrayList anciBioUserList = (ArrayList)anciHash[SWDataHelper.anciBioBoardKey];
                    ArrayList anciChemUserList = (ArrayList)anciHash[SWDataHelper.anciChemBoardKey];
                    ArrayList anciRadUserList = (ArrayList)anciHash[SWDataHelper.anciRadBoardKey];
                    if (anciBioUserList != null)
                    {
                        currentContext.Variables["anciBioUser"].Value = anciBioUserList;
                        //SWDataHelper.AppendArrayList(varAnciArrayList, anciBioUserList);
                        currentContext.Variables["anciBioUserExist"].Value = 1;
                    }

                    if (anciChemUserList != null)
                    {
                        currentContext.Variables["anciChemUser"].Value = anciChemUserList;
                        //SWDataHelper.AppendArrayList(varAnciArrayList, anciChemUserList);
                        currentContext.Variables["anciChemUserExist"].Value = 1;
                    }

                    if (anciRadUserList != null)
                    {
                        currentContext.Variables["anciRadUser"].Value = anciRadUserList;
                        //SWDataHelper.AppendArrayList(varAnciArrayList, anciRadUserList);
                        currentContext.Variables["anciRadUserExist"].Value = 1;
                    }
                }
                else
                    currentContext.Variables["boardUsersExist"].Value = 0;

                //Get Non Critical Study Staff users	
                ArrayList varNCSSArrayList = new ArrayList();
                ArrayList varCSSArrayList = new ArrayList();
                int addedPIUserId = 0;
                varNCSSArrayList = AnimalsWF.GetStudyStaffUsers(Int32.Parse(currentContext.Contents["ppid"].Value.ToString()), out varCSSArrayList, out addedPIUserId);
                currentContext.Variables["addedPIUserId"].Value = addedPIUserId;
                currentContext.Variables["cSSUsers"].Value = varCSSArrayList;

                if ((varCSSArrayList != null) && (varCSSArrayList.Count > 0))
                    currentContext.Variables["cSSUsersExist"].Value = 1;
                else
                    currentContext.Variables["cSSUsersExist"].Value = 0;

                currentContext.Variables["ncssUser"].Value = varNCSSArrayList;
                if ((varNCSSArrayList != null) && (varNCSSArrayList.Count > 0))
                    currentContext.Variables["ncssUsersExist"].Value = 1;
                else
                    currentContext.Variables["ncssUsersExist"].Value = 0;

                if (currentContext.Contents["workflowtype"].Value != null)
                    currentContext.Variables["workflowType"].Value = currentContext.Contents["workflowtype"].Value;

                currentContext.SaveVariables();
                output = "Success";
            }
            catch (Exception ex)
            {
                logger.LogMessage(ReasonConst.Error, "Unable to set workflow variables in SetWorkFlowVariables.Run() " + ex.ToString());
                output = "Failure";
            }
            finally
            {
                AnimalsWF.Dispose();
            }
            return WorFlowInterface.ActionResult.Completed;
        }

        /// <summary>
        /// Gets the web control to be displayed in the activity list for this action. No user interface is implemented for
        /// this action. So it returns null.
        /// </summary>
        /// <returns>IActivityWebUIHandler - Interface that allows an object to implement a custom document view Control.</returns>
        public virtual Workflow.NET.Interfaces.IActivityWebUIHandler GetActivityWebUIHandler()
        {
            return null;
        }

    }
    #endregion
}
